/**
 * Ajax 工具集
 */

/**
 * 
 * ajax({
			    type:"post",
			    url:url,
			    data:{},
			    dataType:"json",
			    success:function(data){
			        console.log(data);
			    }
			});
 * 
 * 
 */
var ajax = function(conf) {
    // 初始化
    //type参数,可选
    var type = conf.type;
    //url参数，必填 
    var url = conf.url;
    //data参数可选，只有在post请求时需要
    var data = conf.data;
    //datatype参数可选    
    var dataType = conf.dataType;
    //回调函数可选
    var success = conf.success;
    // true 为异步，false 为同步
    var async = conf.async;
                                                                                         
    if (type == null){
        //type参数可选，默认为get
        type = "get";
    }
    if (dataType == null){
        //dataType参数可选，默认为text
        dataType = "text";
    }
    if(async == null){
    	async = true;
    }
    // 创建ajax引擎对象
    var xhr = createAjax();
    // 打开
    xhr.open(type, url, false);
    // 发送
    if (type == "GET" || type == "get") {
        xhr.send(null);
    } else if (type == "POST" || type == "post") {
        xhr.setRequestHeader("content-type",
                    "application/x-www-form-urlencoded");
        xhr.send(data);
    }
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            if(dataType == "text"||dataType=="TEXT") {
                if (success != null){
                    //普通文本
                    success(xhr.responseText);
                }
            }else if(dataType=="xml"||dataType=="XML") {
                if (success != null){
                    //接收xml文档    
                    success(xhr.responseXML);
                }  
            }else if(dataType=="json"||dataType=="JSON") {
                if (success != null){
                    //将json字符串转换为js对象  
                    success(eval("("+xhr.responseText+")"));
                }
            }
        }
    };
    
};
ajax.prototype = {
	createAjax : function() {
		var oAjax = null;
		if(window.XMLHttpRequest){
		    oAjax = new XMLHttpRequest();
		}else{
		    oAjax = new ActiveXObject("Microsoft.XMLHTTP");
		}
	    return oAjax;
	},
	formatJson : function (json, options) {
		var reg = null,
		formatted = '',
		pad = 0,
		PADDING = '    '; // one can also use '\t' or a different number of spaces
 
		// optional settings
		options = options || {};
		// remove newline where '{' or '[' follows ':'
		options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
		// use a space after a colon
		options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
	 
		// begin formatting...
		if (typeof json !== 'string') {
			// make sure we start with the JSON as a string
			json = JSON.stringify(json);
		} else {
			// is already a string, so parse and re-stringify in order to remove extra whitespace
			json = JSON.parse(json);
			json = JSON.stringify(json);
		}
	 
		// add newline before and after curly braces
		reg = /([\{\}])/g;
		json = json.replace(reg, '\r\n$1\r\n');
	 
		// add newline before and after square brackets
		reg = /([\[\]])/g;
		json = json.replace(reg, '\r\n$1\r\n');
	 
		// add newline after comma
		reg = /(\,)/g;
		json = json.replace(reg, '$1\r\n');
	 
		// remove multiple newlines
		reg = /(\r\n\r\n)/g;
		json = json.replace(reg, '\r\n');
	 
		// remove newlines before commas
		reg = /\r\n\,/g;
		json = json.replace(reg, ',');
	 
		// optional formatting...
		if (!options.newlineAfterColonIfBeforeBraceOrBracket) {			
			reg = /\:\r\n\{/g;
			json = json.replace(reg, ':{');
			reg = /\:\r\n\[/g;
			json = json.replace(reg, ':[');
		}
		if (options.spaceAfterColon) {			
			reg = /\:/g;
			json = json.replace(reg, ':');
		}
	 
		$.each(json.split('\r\n'), function(index, node) {
			var i = 0,
				indent = 0,
				padding = '';
	 
			if (node.match(/\{$/) || node.match(/\[$/)) {
				indent = 1;
			} else if (node.match(/\}/) || node.match(/\]/)) {
				if (pad !== 0) {
					pad -= 1;
				}
			} else {
				indent = 0;
			}
	 
			for (i = 0; i < pad; i++) {
				padding += PADDING;
			}
	 
			formatted += padding + node + '\r\n';
			pad += indent;
		});
	 
		return formatted;
	}
};



var XHRFactory = function() {
	this.init.apply(this, arguments);
};

XHRFactory.prototype = {
	init : function() {
		this.xhr = this.create();
	},
	create : function() {
		var xhr = null;
		try {
			if (window.XMLHttpRequest) {
				xhr = new XMLHttpRequest();
			} else if (window.ActiveXObject) {
				xhr = new ActiveXObject("Msxml2.Xmlhttp");
			}
		} catch (err) {
			xhr = new ActiveXObject("Microsoft.Xmlhttp");
		}
		return xhr;
	},
	readystate : function(timeout, callback) {
		this.xhr.onreadystatechange = function() {
			if (this.readyState == 4 && this.status == 200) {
				callback(eval("(" + this.responseText + ")"));
			} else {
				setTimeout(function() {
					this.xhr.abort();
				}, !timeout ? 15000 : timeout);
			}

		}
	},
	para : function(data) {
		var datastr = "";
		if (data && Object.prototype.toString.call(data) == "[object Object]") {
			for ( var i in data) {
				for (var i = 0; i < length; i++) {
					datastr += i + "=" + data[i] + "&";
				}
			}
		}
		return datastr;
	},
	get : function(url, data, callback, async, timeout) {
		this.readystate(timeout, callback);
		var newurl = url;
		var datastr = this.para(data);
		newurl = url + "?" + datastr;
		this.xhr.open("get", newurl, !async ? true : async);
		this.xhr.send(null);
	},
	post : function(url, data, callback, async, timeout) {
		this.readystate(timeout, callback);
		var newurl = url;
		var datastr = this.para(data);
		this.xhr.open("post", newurl, !async ? true : async);
		//this.xhr.setRequestHeader("content-type", "x-www-form-urlencoded");
		this.xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
		this.xhr.send(!datastr ? null : datastr);
	}

};
